﻿namespace System.ComponentModel.Composition.SilverlightControlExtensions.Controls
{
    using System.ComponentModel.Composition.Hosting;
    using System.ComponentModel.Composition.SilverlightControlExtensions.Infrastructure;
    using System.Linq;
    using System.Windows;
    using System.Windows.Controls;

    public class MefContentControl : ContentControl
    {
        public static readonly DependencyProperty ContractProperty = DependencyProperty.Register(
            "Contract", typeof(string), typeof(MefContentControl), new PropertyMetadata(string.Empty));

        public string Contract
        {
            get
            {
                return (string)this.GetValue(ContractProperty);
            }

            set
            {
                this.SetValue(ContractProperty, value);
                this.InterogateExportProvider();
            }
        }

        private void InterogateExportProvider()
        {
            var exportsProvider = Application.Current.GetApplicationExportProvider();

            var exportedValues = exportsProvider.GetExportedValues<object>(this.Contract);
            if (exportedValues.Count() <= 0)
            {
                exportsProvider.ExportsChanged += this.MefItemsControlExportsChanged;
            }
            else
            {
                this.Content = exportedValues.Single();
            }
        }

        private void MefItemsControlExportsChanged(object sender, ExportsChangeEventArgs e)
        {
            if (e.AddedExports.Any(x => x.ContractName == this.Contract))
            {
                this.Content = Application.Current.GetApplicationExportProvider().GetExportedValue<object>(
                    this.Contract);
            }
        }
    }
}